<script setup>
import { ref, watch } from 'vue'
import { formatDate } from '@/utils/format'
import { getCommentList } from '@/api/comment'
import { get, post } from '@/api/request'
import { ElMessage } from 'element-plus'

// 数据定义
const comments = ref([])
const queryParams = ref({
  pageNo: 1,
  size: 7,
  search: ''
})
const total = ref(0)
const sortOptions = ref([
  { label: '按 ID 排序', value: 'id' },
  { label: '按点赞数排序', value: 'likes' }
])
const selectedSort = ref('id') // 默认按 ID 排序

// 获取评论列表
const getComments = async () => {
  try {
    const { data } = await getCommentList(queryParams.value)
    comments.value = data.records.filter(record => record.songListId !== null && record.songListId !== undefined)
    total.value = data.total
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

// 按点赞数获取评论列表
const getCommentsByLikes = async () => {
  try {
    const { data } = await get('/comment/pageByLikes', queryParams.value)
    comments.value = data.records.filter(record => record.songId !== null && record.songId !== undefined)
    total.value = data.total
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

// 根据选择的排序方式获取评论
const fetchComments = () => {
  queryParams.value.pageNo = 1
  if (selectedSort.value === 'likes') {
    getCommentsByLikes()
  } else {
    getComments()
  }
}

// 初始化加载数据
fetchComments()

// 分页切换
const handlePageChange = (pageNo) => {
  queryParams.value.pageNo = pageNo
  if (selectedSort.value === 'likes') {
    getCommentsByLikes()
  } else {
    getComments()
  }
}

// 搜索功能
const handleSearch = () => {
  queryParams.value.pageNo = 1
  fetchComments()
}

// 点赞操作
const upComment = async (row) => {
  try {
    const response = await get('/comment/like', { id: row.id })
    if (response.code == '0') {
      row.up += 1
      ElMessage.success(response.msg)
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('点赞失败，请稍后重试')
  }
}

// 删除操作
const handleDeleteComment = async (row) => {
  try {
    const response = await get('/comment/delete', { id: row.id })
    if (response.code == '0') {
      ElMessage.success(response.msg)
      comments.value = comments.value.filter(item => item.id !== row.id)
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    console.error('删除评论失败:', error)
    ElMessage.error('删除评论失败，请稍后重试')
  }
}

// 监听查询参数变化
watch(queryParams, () => {
  // 可以在这里添加防抖逻辑
}, { deep: true })
</script>

<template>
  <el-card>
    <template #header>
      <el-form :inline="true" :model="queryParams" label-width="auto">
        <el-form-item label="评论">
          <el-input
              placeholder="请输入评论信息"
              v-model="queryParams.search"
              clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜</el-button>
        </el-form-item>
        <el-form-item>
          <el-select v-model="selectedSort" placeholder="请选择排序方式" @change="fetchComments">
            <el-option
                v-for="option in sortOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </template>

    <el-table :data="comments" style="width: 100%">
      <el-table-column prop="id" label="编号" />
      <el-table-column label="用户ID" prop="userId" />
      <el-table-column label="评论内容" prop="content" />
      <el-table-column prop="up" label="点赞" />
      <el-table-column prop="create_time" label="日期" :formatter="formatDate" />
      <el-table-column label="歌单id" prop="songListId">
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" @click="upComment(row)">点赞</el-button>
          <el-button type="danger" @click="handleDeleteComment(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="queryParams.size"
          :current-page="queryParams.pageNo"
          @current-change="handlePageChange"
      />
    </div>
  </el-card>
</template>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}

:deep(.el-card) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}
</style>